package com.mp3player.download;

import com.mp3player.util.FileUtils;
import com.mp3player.util.MetaData;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Cuckoo322 on 3/18/2017.
 */

public class HttpDownloader {

    /**
     * 根据URL地址下载文本文件
     * @param urlStr 文本文件的地址
     * @return 下载下来的文本（字符串形式）
     */
    public String downloadTextFile(String urlStr) {
        StringBuilder sb = new StringBuilder();
        String line = null;
        BufferedReader br = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 下载非文本文件
     * @param urlStr 文件资源所在的url地址
     * @param path 文件下载后存放的路径
     * @param fileName 文件下载后保存的文件名
     * @return -1：下载出错<br/>0：下载成功<br/>1：文件已经存在
     */
    public int downloadBinaryFile(String urlStr, String path, String fileName) {
        InputStream inputStream = null;
        FileUtils fileUtils = new FileUtils(MetaData.root);
        try {
            if (fileUtils.isFileExist(fileName, path)) {
                return 1;
            } else {
                inputStream = getInputStreamFromURL(urlStr);
                File downloadFile = fileUtils.writeFromInput(path, fileName, inputStream);
                if (downloadFile.length() < 10) {
                    return -1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    public InputStream getInputStreamFromURL (String urlStr) {
        InputStream inputStream = null;
        try {
            URL url = new URL(urlStr);
            inputStream = url.openStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }
}
